package org.springtest.test;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	AccountService accountService;
	
	@Autowired
	PasswordEncoder passwordEncoder;

	@Autowired
	SaltSource saltSource;
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value="/", method=RequestMethod.GET)
	public String home() {
		logger.info("Welcome home!");
		return "home";
	}
	
	@RequestMapping(value = "/administrator/add", method = RequestMethod.GET)  
	public ModelAndView adminAdd() {		
		logger.info("called 'add'");
		ModelAndView mav = new ModelAndView("/administrator/add");  
		mav.addObject("administrator", new Administrator());  
		return mav;  
	} 
	
	@RequestMapping(value = "/administrator/add", method = RequestMethod.POST)  
	public ModelAndView add(Administrator admin, BindingResult result) {		
		if (passwordEncoder == null)
			System.out.println("[HomeController] passwordEncoder is null");
		else
			System.out.println("[HomeController] passwordEncoder is not null");
		if (saltSource == null)
			System.out.println("[HomeController] saltSource is null");
		else
			System.out.println("[HomeController] saltSource is not null");
		
		ModelAndView mav = new ModelAndView("administrator/add");
		
		if (admin.getUsername().length() == 0) {  
			result.addError(new FieldError("administrator", "username",  "notSupplied"));  
		}
		
		if (admin.getPassword().length() == 0) {  
			result.addError(new FieldError("administrator", "password",  "notSupplied"));  
		}
		
		if (admin.getPassword().length() == 0) {  
			result.addError(new FieldError("administrator", "repeatedPassword",  "notSupplied"));  
		}
		
		if (!admin.getPassword().equals(admin.getRepeatedPassword())) {  
			result.addError(new FieldError("administrator", "repeatedPassword",  "notEqual"));  
		}
		
		if (result.hasErrors()) {  
			mav.addObject("administrator", admin);  
			return mav;  
		}  
		
		List<AccountRole> ar = new ArrayList<AccountRole>();  
		ar.add(new AccountRole("ROLE_ADMIN"));
		
		try {  
			accountService.registerAccount(admin, ar);  
		} catch (UserExistsException e) {  
			logger.info("user exists");
			//result.reject("user.exists");
			result.addError(new FieldError("administrator", "username",  "userExists"));
			admin.setUsername("???");
			mav.addObject("administrator", admin);  
			return mav;  
		}  
		
		mav.setViewName("redirect:/administrator.html");  
		return mav;
	}
	
	@RequestMapping(value = "/administrator")
	public ModelAndView index() {
		ModelAndView mav = new ModelAndView("/administrator/index");
		List<AccountRole> roles = new ArrayList<AccountRole>();
		roles.add(new AccountRole("ROLE_ADMIN"));
		List<Account> acc = (List<Account>) accountService.listAccounts(roles);
		mav.addObject("accounts", acc);
		return mav;
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(@RequestParam(value = "error", required = false, defaultValue = "false") boolean error) {
		ModelAndView mav = new ModelAndView("index/login");
		mav.addObject("isError", error);
		return mav;
	}
}

